import { useStore } from '@/hooks';
import { Button, Dialog, Form } from '@alifd/next';
import React, { useEffect, useRef, useState } from 'react';
import { t } from '@lingui/macro';
import DrawerFooter from '@/components/DrawerFooter';
import { FieldsGrid } from '../stores/definitions';
import { observer } from 'mobx-react-lite';
import { observable } from 'mobx';
import TauSimpleSelect from '@/components/TauSimpleSelect';

const FromItem = Form.Item;
const formItemLayout = {
  labelCol: {
    fixedSpan: 8,
  },
  wrapperCol: {
    span: 14,
  },
  style: { marginBottom: 20 },
};

const DataForm = ({ modal, dispatchInfo, onCancel, onSubmit, ...formProps }) => {
  const { dispatcherStore: store } = useStore();
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [dispatch] = useState(() => observable({}));
  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    const args = {
      search: {
        status: 1,
      },
      pg: {
        size: 999,
      },
    };
    store.getCompany({ ...args });
    if (JSON.stringify(dispatchInfo) !== '{}') {
      const data = dispatchInfo;
      editCtx.origin = _.cloneDeep(data);
      _.assign(dispatch, data);
      _.set(dispatch, 'companyId', data?.extra?.companyId);
      _.set(dispatch, 'fullname', data?.extra?.dispatcherName);
    } else if (!global.isAdmin) {
      _.set(dispatch, 'companyId', global?.me?.accountId);
    }
  }, []);

  // 页面重载公司名称
  const overrideModel = {
    companyId: {
      label: t`公司名称`,
      ui: {
        renderer: (v) => <TauSimpleSelect disabled={!global.isAdmin} data={toJS(rootStore.dispatcherStore.company)} value={v} />,
        itemProps: { required: true },
      },
    },
  };

  /**
   * @description 动态回现表单数据
   * @param {*} values
   * @param {*} item 数据Items
   */
  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(dispatch, name, value);
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  /**
   * @description 提交表单实现修改调度员
   * @param {*} r formData
   */
  const handleSubmit = (values, errors) => {
    if (!_.isEmpty(errors)) {
      return;
    }
    onSubmit?.(dispatch);
  };
  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  return (
    <Form
      isPreview={false}
      {...formProps}
      value={dispatch}
      colon
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <FieldsGrid
        formData={dispatch}
        mode={modal[0]}
        columns={1}
        overrideModel={overrideModel}
        itemLayout={{ ...formItemLayout, labelAlign: 'left' }}
        fields={['mobile', 'fullname', 'gender', 'companyId']}
      />
      <DrawerFooter>
        <FromItem>
          <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
    </Form>
  );
};

export default observer(DataForm);
